# -*- coding: utf-8 -*-
"""
Created on 2015年10月10日下午3:01:18

@author: 李鹏飞
定点任务,重启,还在; 过期后重启,不执行,直接删除;
结果: 使用3.0 ; 两个任务表共用,
自建表存所有,过期标记
系统表存任务,持久化任务
过期的判断自建表,执行方法;
重启不用重新加定时器,只要判断过期
"""
import logging

from auction import settings
from auction.libs.apscheduler.events import EVENT_JOB_ERROR
from auction.libs.apscheduler.events import EVENT_JOB_EXECUTED
from auction.libs.apscheduler.executors.pool import ProcessPoolExecutor
from auction.libs.apscheduler.executors.pool import ThreadPoolExecutor
from auction.libs.apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from auction.libs.apscheduler.schedulers.background import BackgroundScheduler

logger = logging.getLogger(__name__)

db = settings.DATABASES['default']
jobstores = {
    # 任务存储在数据库
    'default': SQLAlchemyJobStore(url='mysql://%s:%s@%s:%s/%s?charset=utf8'
                                      % (db['USER'], db['PASSWORD'], db['HOST'], db['PORT'], db['NAME']))
}
executors = {  # 线程
    'default': ThreadPoolExecutor(20),
    'processpool': ProcessPoolExecutor(5)
}
job_defaults = {
    'coalesce': False,
    'max_instances': 100  # 同时进行几个任务
}

scheduler = BackgroundScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults)
# 开始启动定时
scheduler.start()


def event_listener(event):
    """定时任务监听器"""
    if event.exception:
        logger.info('任务[%s]执行时间[%s]报错[%s]' % (event.job_id, event.scheduled_run_time, event.exception))


# 加报错时监听器
scheduler.add_listener(event_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)


# def myfunc():
#     # 改存数据库
#     # a=int('as')
#     logger.info('aps测试22222[%s]'%'aaa')
#     # Advert.objects.create(image='11112222', link='2222222222')
#
# import datetime
# run_time = datetime.datetime.now() + datetime.timedelta(minutes=1)
# job = scheduler.add_job(myfunc, 'date', id='qweqwe2', run_date=run_time, replace_existing=True)
# print job
